package org.boticelli.plugin.twitter;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpVersion;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;

public class HttpClientFactory
{
    private ThreadSafeClientConnManager clientConnectionManager;
    private BasicHttpParams params;

    public HttpClientFactory() throws NoSuchAlgorithmException, KeyManagementException
    {
        SchemeRegistry supportedSchemes = new SchemeRegistry();
        SocketFactory sf = PlainSocketFactory.getSocketFactory();
        
        SSLContext instance = SSLContext.getInstance("TLS");
        instance.init(null,null,null);
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(
                instance);
        Scheme https = new Scheme("https", sslSocketFactory, 443);

        supportedSchemes.register(https);
        supportedSchemes.register(new Scheme("http", sf, 80));
        
        params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setUseExpectContinue(params, false);
        ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(4));
        ConnManagerParams.setMaxTotalConnections(params, 20);

        clientConnectionManager = new ThreadSafeClientConnManager( params, supportedSchemes);
    }
    
    public DefaultHttpClient createHttpClient()
    {
        return new DefaultHttpClient(clientConnectionManager, params);
    }
}
